<template>
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item>咨询师管理</el-breadcrumb-item>
		<el-breadcrumb-item>咨询师等级管理</el-breadcrumb-item>
	</el-breadcrumb>

	<!-- 行内表单 -->
	<el-form :inline="true" :model="queryInfo" class="demo-form-inline">
		<el-form-item label="等级">
			<el-input v-model="queryInfo.levelName" placeholder="请输入等级" clearable @clear="query" />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="query">搜索</el-button>
			<el-button type="primary" @click="add">新增等级</el-button>
			<el-button type="danger" @click="batchRemove">批量删除</el-button>
		</el-form-item>

	</el-form>

	<!-- 数据表格 -->
	<el-table :data="dataList" style="width: 100%" @selection-change="handleSelectionChange" border row-key="id">
		<el-table-column fixed="left" type="selection" width="55" />
		<el-table-column fixed="left" prop="id" label="id" width="60" />
		<el-table-column prop="levelName" label="等级" />
		<el-table-column fixed="right" label="操作" min-width="120" class-name="operation-column">
			<template #default="scope">
				<el-button type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
				<el-button type="danger" size="small" @click="remove(scope.row.id)">删除</el-button>
			</template>
		</el-table-column>
	</el-table>


	<!-- 分页区域 -->
	<el-pagination v-model:current-page="queryInfo.pageNum" v-model:page-size="queryInfo.pageSize"
		:page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="total"
		@size-change="handleSizeChange" @current-change="handleCurrentChange" />

	<!-- 新增/编辑对话框 -->
	<el-dialog :title="title" v-model="dialogFormVisible" width="950" @close="cancle">
		<el-form :model="LevelData" label-width="100">
			<el-form-item label="等级">
				<el-input v-model="LevelData.levelName" autocomplete="off" placeholder="请输入等级"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="cancle">取 消</el-button>
				<el-button type="primary" @click="confirm">确 定</el-button>
			</div>
		</template>
	</el-dialog>

</template>

<script setup>
	import {
		getCurrentInstance,
		reactive
	} from 'vue';
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus';
	import {
		Plus
	} from '@element-plus/icons-vue';

	/* 查询信息对象 */
	const queryInfo = reactive({
		levelName: "",
		pageNum: 1,
		pageSize: 5
	})

	//当前页数据
	const dataList = ref([])

	//存储复选数据
	const multipleSelection = ref([])
	const handleSelectionChange = (val) => {
		multipleSelection.value = val.map(item => {
			return item.id
		})
		console.log(multipleSelection.value);
	}


	const total = ref(0);

	const axios = getCurrentInstance().appContext.config.globalProperties.axios;
	//查询数据的函数
	const query = () => {
		axios.get(`/consultantLevel/page`, {
				params: queryInfo
			})
			.then((res) => {
				if (!res || !Array.isArray(res.list)) {
					dataList.value = []
					total.value = 0
					ElMessage.error("数据加载失败")
					return
				}
				dataList.value = res.list.map(item => ({
					id: item.id,
					levelName: item.levelName,
					del: item.del ?? 0
				}))
				total.value = res.total || 0
			}).catch(error => {
				ElMessage.error("查询失败")
			})
	};

	//组件加载完毕，查询数据
	onMounted(() => {
		query();
	});
	//每页显示条目数改变
	const handleSizeChange = (val) => {
		queryInfo.pageSize = val;
		query();
	};
	//页码改变
	const handleCurrentChange = (val) => {
		queryInfo.pageNum = val;
		query();
	};

	const title = ref('新增等级')
	const dialogFormVisible = ref(false)
	//新增修改数据集
	const LevelData = ref({
		id: "",
		levelName: '',
		del: 0,
	})

	//当点击关闭按钮 或 取消按钮的时候，重置表单
	const cancle = () => {
		console.log('你点击了取消按钮');
		LevelData.value = {
			id: "",
			levelName: '',
			del: 0,
		}
		dialogFormVisible.value = false
	}

	//确定按钮
	const confirm = () => {
		console.log('你点击了确定按钮');
		if (LevelData.value.id) { //数据存在id，修改
			axios.put(`/consultantLevel/${LevelData.value.id}`, LevelData.value)
				.then((resp) => {
					if (resp.includes('成功')) {
						ElMessage.success('修改成功')
						dialogFormVisible.value = false
						query();
					} else {
						ElMessage.error('修改失败' + resp)
					}
					query();
					dialogFormVisible.value = false
				})
		} else { //新增
			axios.post('consultantLevel', LevelData.value)
				.then((resp) => {
					if (resp.includes('成功')) {
						ElMessage.success('新增成功')
						dialogFormVisible.value = false
						queryInfo.levelName = ''
						query()
					} else {
						ElMessage.error('新增失败' + resp)
					}
				})
				.catch(() => {
					ElMessage.error("新增请求失败")
				})
		}
	}

	//点击新增按钮的时候，弹出对话框
	const add = () => {
		title.value = '新增等级'
		dialogFormVisible.value = true
	}
	//编辑
	const edit = (row) => {
		title.value = '编辑等级'
		dialogFormVisible.value = true
		LevelData.value = row
	}
	// 单个删除
	const remove = (id) => {
		if (!id) {
			ElMessage.warning("无效的删除目标");
			return;
		}

		ElMessageBox.confirm('此操作将永久删除该等级, 是否继续?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		}).then(() => {
			axios.delete(`/consultantLevel/${id}`)
				.then(resp => {
					// 成功处理（保持不变）
					if (resp.includes('成功')) {
						ElMessage.success('删除成功');
						query();
					} else {
						ElMessage.error('删除失败: ' + resp.data);
					}
				})
				// 新增：捕获后端抛出的异常（如关联咨询师时）
				.catch(error => {
					// 提取后端异常消息（根据实际响应结构调整）
					const errorMsg = error.response?.data?.message || error.message || '删除失败，请检查是否有关联的咨询师';
					ElMessage.error(errorMsg);
				});
		}).catch(() => {
			// 取消删除的提示（保持不变）
			ElMessage({
				type: 'info',
				message: '已取消删除'
			});
		});
	};

	// 批量删除
	const batchRemove = () => {
		if (multipleSelection.value.length === 0) {
			ElMessage.warning('请选择要删除的等级');
			return;
		}

		ElMessageBox.confirm('此操作将永久删除选中等级, 是否继续?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		}).then(() => {
			axios.delete('/consultantLevel', {
					params: {
						ids: multipleSelection.value.join(',')
					}
				}).then(resp => {
					// 成功处理（保持不变）
					if (resp.includes('成功')) {
						ElMessage.success('批量删除成功');
						query();
						multipleSelection.value = [];
					} else {
						ElMessage.error('批量删除失败: ' + resp.data);
					}
				})
				// 新增：捕获后端抛出的异常（如关联咨询师时）
				.catch(error => {
					const errorMsg = error.response?.data?.message || error.message ||
						'批量删除失败，请检查是否有关联的咨询师';
					ElMessage.error(errorMsg);
				});
		}).catch(() => {
			// 取消删除的提示（保持不变）
			ElMessage({
				type: 'info',
				message: '已取消删除'
			});
		});
	};
</script>
<!-- 等级列表的 style 部分修改 -->
<style>
	/* 移除 scoped，让样式作用于组件内部所有元素 */
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-breadcrumb {
		margin-bottom: 15px;
		padding: 0 0 15px;
		border-bottom: 1px solid #ddd ;
	}

	.el-pagination {
		margin-top: 15px;
		/* 确保分页与表格的间距紧凑 */
	}

	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}

	.demo-form-inline .el-select {
		--el-select-width: 220px;
	}

	/* 确保表格占满宽度，减少留白 */
	.el-table {
		width: 100% ;
		margin-bottom: 15px;
		/* 表格与分页的间距 */
	}
</style>